package com.zhangyx.spider.music;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhangyx.comm.RedisUtil;
import com.zhangyx.core.Page;
import com.zhangyx.core.Processor;
import org.apache.log4j.Logger;

import java.util.Map;

import static com.zhangyx.spider.music.Config.song_page_requst;

public class UserProcessor extends Processor {

    private static Logger log = Logger.getLogger(UserProcessor.class);
    @Override
    public int interval() {
        return 0;
    }

    @Override
    public void core() throws Exception {
        Page downPage = getNextPage(Config.user_page_reponse);
        JSONArray array = JSONObject.parseObject(downPage.getHtml()).getJSONArray("allData");
        if (array == null || array.size() == 0) {
            log.info("网页解析失败。"+downPage.getHtml());
            return;
        }
        for (Object obj : array) {
            JSONObject jsonObject = (JSONObject) obj;
            jsonObject = jsonObject.getJSONObject("song");
            int id = jsonObject.getInteger("id");
            String name = jsonObject.getString("name");

            //song

            String para = "{\"rid\":\"R_SO_4_##\",\"offset\":\"**\",\"total\":\"false\",\"limit\":\"20\",\"csrf_token\":\"\"}";
            String baseUrl = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_355961?csrf_token=";

            String repeat_key = baseUrl + "####" + id;
            if (RedisUtil.isExist(repeat_key)) {
                return;
            }
            String thisPata = para.replace("##", String.valueOf(id)).replace("**", String.valueOf(0));
            Map<String, String> entityStr = Config.encrypt(thisPata);
            Page thispage = new Page();
            thispage.setUseGET(false);
            thispage.setUrl(baseUrl);
            thispage.setRequestCookies(Config.getCookies());
            Map<String, String> header = Config.getHeaders();
            header.put("Referer", "http://music.163.com/song?id=" + id);
            thispage.setHeader(header);
            thispage.setEntity(entityStr);
            thispage.getTemp().put("song_id", String.valueOf(id));
            RedisUtil.pushStackObj(song_page_requst, thispage);
            log.info("user --> song " + id);
        }
    }
}
